'use strict';

const AV = require('leanengine')
const Promise = require('bluebird')

const Match = require('../libs/Match')

var func = {

  all (req) {
    var query = new AV.Query(AV.User)
    query.notEqualTo('objectId', req.user.id)
    return query.find()
  },

  getUserObjByIds (req) {
    var promises = req.params.userObjIds.map(id => {
      var cql = `select * from _User where objectId = '${id}'`
      return AV.Query.doCloudQuery(cql)
    })
    return Promise.all(promises).then(ret => {
      return Promise.resolve(ret.map(el => el.results[0]))
    })
  },

  genTestUsers () {
    var promises = []
    for (var i = 1; i < 5; i++) {
      var user = new AV.Object('_User')
      promises.push(user.save({
        nickname: '青年队第' + i + '双打2',
        username: 'teen' + i + 'doubles2',
        password: '123',
        sex: 1
      }))
    }
    return Promise.all(promises)
  },

  genDoubles () {
    var promises = []
    var arr1 = ['57ecc4560bd1d000586f8c6f','57ecc4560bd1d000586f8c6e','57ecc4562e958a0055382047','57ecc4197db2a20059fec570', '57ecc4190e3dd900576fa236','57ecc4190bd1d000586f8aa8','57ecc419da2f60004f44f1a4']
    var arr2 = ['57ecc4300bd1d000586f8b49','57ecc466a0bb9f0058e7237e','57ecc4660bd1d000586f8cd5','57ecc430816dfa00566872a9', '57ecc4300bd1d000586f8b49','57ecc430da2f60004f44f266','57ecc430816dfa00566872aa']
    // for (var i = 1; i < 5; i++) {
    arr1.forEach((el, index) => {
      var doubles = new AV.Object('Doubles')
      var relation = doubles.relation('players')
      relation.add(new AV.Object.createWithoutData('_User', el))
      relation.add(new AV.Object.createWithoutData('_User', arr2[index]))
      promises.push(doubles.save())
    })
      // promises.push(user.save({
      //   nickname: '青年队第' + i + '双打2',
      //   username: 'teen' + i + 'doubles2',
      //   password: '123',
      //   sex: 1
      // }))
    // }
    return Promise.all(promises)
  },

  getS () {

  }
}


AV.Cloud.define('user', function (req, res) {
  var promise
  if (!req.user) {
    promise = Promise.reject({
      msg: 'not loged in'
    })
  } else {
    promise = func[req.params.method](req)
  }
  return promise.then(function (ret) {
    res.success(ret)
  }).catch(function (err) {
    console.log(err)
    res.error(err)
  })
})
